﻿using ByteSite.Common;
using ByteSite.Quartz;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
using Yitter.IdGenerator;

namespace ByteSite.Web
{
    public class Global : System.Web.HttpApplication
    {

        //定时任务
        public static readonly QuartzHelper quartz = new QuartzHelper();
        protected void Application_Start(object sender, EventArgs e)
        {
            //全局初始化设置WorkerId，默认最大2^16-1。（初始化过程全局只需一次，且必须最先设置）
            var options = new IdGeneratorOptions() { WorkerId = 1 };
            YitIdHelper.SetIdGenerator(options);

            //启动定时任务
            quartz.Start().GetAwaiter();

            //启动websocket
            WebSocketManager.Init();
        }

        protected void Session_Start(object sender, EventArgs e)
        {

        }

        protected void Application_BeginRequest(object sender, EventArgs e)
        {

        }

        protected void Application_AuthenticateRequest(object sender, EventArgs e)
        {

        }

        protected void Application_Error(object sender, EventArgs e)
        {

        }

        protected void Session_End(object sender, EventArgs e)
        {

        }

        protected void Application_End(object sender, EventArgs e)
        {
            Activate();
        }

        /// <summary>
        /// 激活程序 
        /// IIS回收后，将触发Application_End事件，需发起一次请求才会触发 Application_Start事件开始执行定时任务
        /// </summary>
        public static void Activate()
        {
            WebClient refresh = new WebClient(); 
            try 
            {
                BLL.sysconfig bll = new BLL.sysconfig();
                Entitys.sysconfig config = bll.loadConfig();
                if (config.weburl.ToLower().StartsWith("http://") || config.weburl.ToLower().StartsWith("https://"))
                {
                    refresh.UploadString(config.weburl, string.Empty);
                }
            } 
            catch (Exception ex) 
            {

            }
            finally 
            {
                refresh.Dispose(); 
            }
        }
    }
}